package com.lyons.easyweb.modular.fileInfo.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyons.easyweb.core.util.StringUtils;
import com.lyons.easyweb.modular.config.service.ConfigService;
import com.lyons.easyweb.modular.fileInfo.dao.FileInfoMapper;
import com.lyons.easyweb.modular.fileInfo.pojo.FileInfo;
import com.lyons.easyweb.modular.fileInfo.service.FileInfoService;

/**
 * <p>
 * 文件信息表 服务实现类
 * </p>
 *
 * @author Lyons
 * @since 2021-07-01
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements FileInfoService {

	@Autowired
	ConfigService configService;

	@Autowired
	private FileInfoService fileInfoService;

	@Override
	public String upload(MultipartFile multipartFile) throws IllegalStateException, IOException {

		String path = configService.getFilePath();

		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}

		// 文件后缀
		String fileTyle = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1, multipartFile.getOriginalFilename().length());

		FileInfo fileInfo = FileInfo.builder().fileLocation(4).fileBucket("defaultBucket").fileOriginName(multipartFile.getOriginalFilename()).build();

		fileInfo.setFileSuffix(fileTyle);
		fileInfo.setFileObjectName(StringUtils.getSnowflake());

		File sfile = new File(path, fileInfo.getFileObjectName() + "." + fileInfo.getFileSuffix());
		multipartFile.transferTo(sfile);

		fileInfo.setFilePath(sfile.getAbsolutePath());
		fileInfoService.save(fileInfo);

		return sfile.getAbsolutePath();
	}

	@Override
	public List<FileInfo> listAll() {

		LambdaQueryWrapper<FileInfo> queryWrapper = new LambdaQueryWrapper<FileInfo>();
		queryWrapper.select(FileInfo::getFileOriginName, FileInfo::getFileSuffix, FileInfo::getId);

		List<FileInfo> list = list(queryWrapper);

		return list;
	}

}
